<template>
  <div class="doAnswerPage">
    <a-card>
      <h1>{{ app.appName }}</h1>
      <p>{{ app.appDesc }}</p>
      <h2 style="margin-bottom: 16px">
        {{ current }}、{{ currentQuestion?.title }}
      </h2>
      <a-space direction="vertical" size="large">
        <a-radio-group
          v-model="currentAnswer"
          :options="currentQuestionOptions"
          @change="doRadioChange"
        />
        <div style="margin-top: 24px">
          <a-space>
            <a-button
              circle
              v-if="current > 1"
              type="primary"
              @click="current -= 1"
              >上一题
            </a-button>
            <a-button
              circle
              :loading="submitting"
              v-if="current === questionContent.length"
              type="primary"
              :disabled="!currentAnswer"
              @click="doSubmit"
              >提交答案
            </a-button>
            <a-button
              circle
              type="primary"
              v-if="current < questionContent.length"
              :disabled="!currentAnswer"
              @click="current += 1"
              >下一题
            </a-button>
          </a-space>
        </div>
      </a-space>
    </a-card>
    {{ answerList }}
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  defineProps,
  onMounted,
  reactive,
  ref,
  watchEffect,
  withDefaults,
} from "vue";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { getAppVoByIdUsingGet } from "@/api/appController";
import { listQuestionVoByPageUsingPost } from "@/api/questionController";
import {
  addUserAnswerUsingPost,
  getOnlyIdUsingGet,
} from "@/api/userAnswerController";
import { useRouter } from "vue-router";

const router = useRouter();

//接收路由的参数
interface Props {
  appId: string;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});
const submitting = ref(false);
//当前的题号（从1开始）
const current = ref(1);
//当前题目
const currentQuestion = ref<API.QuestionContentDTO>({});
//当前答案
const currentAnswer = ref<string>();
//答案列表
//const app = ref<API.AppVO>();：这行代码创建了一个ref，但是没有指定初始值。
// 这意味着app.value的初始值是undefined，你不能直接修改app.value的属性，因为app.value是undefined。
const answerList = ref<string[]>([]);
const app = ref<API.AppVO>({});
const questionContent = ref<API.QuestionContentDTO[]>([]);
//当前题目选项
const currentQuestionOptions = computed(() => {
  return currentQuestion.value?.options
    ? currentQuestion.value?.options.map((option) => {
        return {
          label: `${option.key}：${option.value}`,
          value: option.key,
        };
      })
    : [];
});
const onlyID = ref<number>(0);
const getOnlyId = async () => {
  let res: any = await getOnlyIdUsingGet();
  alert(res.data.data);
  if (res.data.code === 0) {
    onlyID.value = res.data.data as any;
  } else {
    message.error("获取唯一id失败" + res.data.message);
  }
};
watchEffect(() => {
  getOnlyId();
});

const loadDate = async () => {
  if (!props.appId) {
    return;
  }
  //获取应用
  let res: any = await getAppVoByIdUsingGet({
    id: props.appId as any,
  });
  if (res.data.code === 0 && res.data.data) {
    app.value = res.data.data;
  } else {
    message.error("获取应用数据失败" + res.data.message);
  }
  //获取题目
  res = await listQuestionVoByPageUsingPost({
    appId: props.appId as any,
    pageSize: 1,
    current: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.data.code === 0 && res.data.data?.records) {
    questionContent.value = res.data.data.records[0].questionContent; //获取最新问题
  } else {
    message.error("获取题目数据失败" + res.data.message);
  }
};

watchEffect(() => {
  loadDate();
});

// 改变 current 题号后，会自动更新当前题目和答案
watchEffect(() => {
  currentQuestion.value = questionContent.value[current.value - 1] as any;
  currentAnswer.value = answerList.value[current.value - 1];
});
/**
 * 将答案保存到答案的列表中
 * @param value
 */
const doRadioChange = (value: string) => {
  answerList.value[current.value - 1] = value;
};
/**
 * 提交答案列表
 */
const doSubmit = async () => {
  if (!props.appId || !answerList.value.length) {
    return;
  }
  submitting.value = true;
  const res = await addUserAnswerUsingPost({
    id: onlyID.value as any,
    appId: props.appId as any,
    choices: answerList.value,
  });
  if (res.data.code === 0 && res.data.data) {
    //交卷成功之后，后端会返回id
    message.success("交卷成功 两秒钟之后会自动跳转到结果页");
    setTimeout(() => {
      router.push(`/answer/result/${res.data.data}`);
    }, 2000);
  } else {
    message.error("提交答案失败" + res.data.message);
  }
  submitting.value = false;
};
</script>
<style scoped></style>
